package com.zhang.exceltest.modules.common.service;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


@Service
public class ExcelService<T> {


    /**
     * @param request 应该是用来携带请求参数的
     * @param list
     * @param clazz
     * @param title
     * @return
     */
    public ModelAndView exportXls(HttpServletRequest request, List<T> list, Class<T> clazz, String title){
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME,title);
        mv.addObject(NormalExcelConstants.CLASS, clazz);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "导出人:" + "我就是导出人", title));
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }


    /**
     * 还未测试
     * @param request
     * @param response
     * @param clazz
     * @return
     */
    public List<T> doParseExcel(HttpServletRequest request, HttpServletResponse response, Class<T> clazz) {
        //获取上传文件数组
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

        //Excel信息保存载体（方法返回值）
        List<T> result = Collections.emptyList();

        //循环解析上传文件====>>forBegin
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                //解析上传文件为实体类集合
                List<T> list = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
                //将此次循环结果保存到方法返回值中
                result.addAll(list);
            } catch (Exception e) {
                System.out.println("文件导入失败");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //循环上传文件====>>forEnd
        System.out.println("文件导入失败");
        return result;
    }
}
